package com.icehelper.hades.base.log;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class RequestWrapper extends HttpServletRequestWrapper {
  private static final HadesLogger logger = HadesLogger.create(RequestWrapper.class);

  private String body;

  public RequestWrapper(HttpServletRequest request) {
    super(request);
    BufferedReader bufferedReader = null;
    try {
      bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
      body = IOUtils.toString(bufferedReader);
      body = body.replaceAll("\\s+", "");
    } catch (Exception e) {
      logger.error("read requestBody exception :" + e);
    } finally{
      IOUtils.closeQuietly(bufferedReader);
    }
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
    ServletInputStream servletInputStream = new ServletInputStream() {

      public boolean isFinished() {
        return false;
      }

      public boolean isReady() {
        return false;
      }

      public void setReadListener( ReadListener readListener) {
      }

      public int read() throws IOException {
        return byteArrayInputStream.read();
      }
    };
    return servletInputStream;
  }

  @Override
  public BufferedReader getReader() throws IOException {
    return new BufferedReader(new InputStreamReader(this.getInputStream()));
  }

  public String getBody() {
    return this.body;
  }

}
